package com.xlongwei.logserver;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Log4j2Client {
	private static Log logger = LogFactory.getLog(Log4j2Client.class);

	public static void main(String[] args) throws Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		Class<?> threadContextClazz = null;
		Method putMethod = null;
		try {
			threadContextClazz = Class.forName("org.apache.logging.log4j.ThreadContext");
			putMethod = threadContextClazz.getMethod("put", String.class, String.class);
		} catch (Exception e) {
			logger.warn(e.getMessage());
			return;
		}
		AtomicInteger cId = new AtomicInteger(10000);
		while (true) {
			System.out.println("Type a message to send to log server. Type 'q' to quit.");
			String s = reader.readLine();
//			ThreadContext.put("cId", String.valueOf(cId.getAndIncrement()));
			putMethod.invoke(threadContextClazz, "cId", String.valueOf(cId.getAndIncrement()));

			if (s.equals("q")) {
				break;
			} else if ("ex".equals(s)) {
				logger.warn(s, new NullPointerException("none"));
			} else if ("ex2".equals(s)) {
				// {"instant":{"epochSecond":1731657743,"nanoOfSecond":347753000},"thread":"main","level":"WARN","loggerName":"com.xlongwei.logserver.Log4j2Client","message":"ex2","thrown":{"commonElementCount":0,"localizedMessage":"java.lang.NullPointerException","message":"java.lang.NullPointerException","name":"java.lang.RuntimeException","cause":{"commonElementCount":1,"name":"java.lang.NullPointerException"},"extendedStackTrace":[{"classLoaderName":"app","class":"com.xlongwei.logserver.Log4j2Client","method":"main","file":"Log4j2Client.java","line":29,"exact":true,"location":"classes/","version":"?"}]},"contextMap":{"cId":"10002"},"endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","threadId":1,"threadPriority":5}
				logger.warn(s, new RuntimeException(new NullPointerException("cause")));
			} else {
				logger.warn(s);
			}
		}
	}
}
